<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 头部警告区 -->
       <el-alert show-icon title="注意: 只允许为第三级分类设置相关参数!" type="warning" :closable="false">

      </el-alert>

      <!-- 选择商品分类区 -->
      <el-row class="cat_opt">
        <el-col :span="2">
          <span>选择商品分类: </span>
        </el-col>
        <!-- 级联选择器 -->
        <el-col :span="4">
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加动态参数</el-button>
          <!-- 动态参数表格 -->
          <el-table
          :data="manyTableData"
          style="width: 100%" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 使用v-for循环渲染tag标签 -->
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" class="attrvals" closable @close="handleTagClosed(index,scope.row)">
                  {{item}}
                </el-tag>

                <!-- input添加标签输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>

                <!-- 按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
               <template slot-scope="scope">
                 <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
               </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加静态属性</el-button>
          <!-- 静态参数表格 -->
          <el-table
          :data="onlyTableDate"
          style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 使用v-for循环渲染tag标签 -->
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" class="attrvals" closable @close="handleTagClosed(index,scope.row)">
                  {{item}}
                </el-tag>

                <!-- input添加标签输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>

                <!-- 按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
               <template slot-scope="scope">
                 <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
               </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
    :title="'添加'+titleText"
    :visible.sync="addDialogVisible"
    width="50%"
    @close="addDialogClosed">
      <!-- 添加参数的验证表单 -->
      <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog
    :title="'修改'+titleText"
    :visible.sync="editParamsDialogVisible"
    width="50%"
    @close="editDialogClosed">
      <!-- 修改参数的验证表单 -->
      <el-form :model="editParamsForm" :rules="editParamsFormRules" ref="editParamsFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
export default {
  data(){
    return {
      // 商品列表
      cateList:[],

      // 配置级联选择框
      cateProps:{
        value:'cat_id',
        label:'cat_name',
        children:'children',
        expandTrigger: 'hover'
      },

      // 级联选择框双向绑定的数组
      selectedCateKeys:[],

      // 被激活的面板
      activeName:'many',

      // 获取的动态参数列表
      manyTableData:[],

      // 获取的动态参数列表
      onlyTableDate:[],
      
      // 控制添加参数对话框的显示与隐藏
      addDialogVisible:false,

      // 添加参数的表单对象
      addParamsForm:{},

      // 添加参数表单的验证规则对象
      addParamsFormRules:{
        attr_name:[
           { required: true, message: '请输入参数名称', trigger: 'blur' },
        ]
      },

      // 控制修改参数对话框显示与隐藏
      editParamsDialogVisible:false,

      // 修改参数的表单对象
      editParamsForm:{},
      
      // 修改参数表单的验证规则对象
      editParamsFormRules:{
        attr_name:[
           { required: true, message: '请输入参数名称', trigger: 'blur' },
        ]
      }


    }
  },
  computed:{
    // 按钮是否被禁用，取决于级联选择器选的个数
    isBtnDisabled(){
      return this.selectedCateKeys.length !== 3 ? true: false;
    },
    // 当前选中的三级id
    cateId(){
      if (this.selectedCateKeys.length===3){
        return this.selectedCateKeys[2];
      }
      return null;
    },

    // 动态计算标题的文本，根据activeName
    titleText(){
      if(this.activeName==='many') return '动态参数';
      return '静态属性';
    }

  },
  created(){
    this.getCateList();
  },
  methods:{
    async getCateList(){
      const {data:res} = await this.$http.get('categories');
      if(res.meta.status!==200) return this.$message.error('获取商品分类失败');
      this.cateList = res.data;
      console.log(this.cateList);
    },

    // 把获取参数列表的代码抽离出来，当级联选择器改变 或 激活面版改变时，都调用它，重新获取参数列表
    async getParamsList(){
      // 如果选的是三级id，根据所选的id和激活的面板发起请求
      const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}});

      if(res.meta.status!==200) return this.$message.error('请求参数失败');
      console.log(res.data);

      // item的每一项attr_vals字符串变成数组attr_vals，方便展开项的渲染，这样即使是空白的item，分割后也会有一个空白项！！
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [];

        // 每一行数据都有自己的条件显示和值，scope.row.inputVisible scope.row.inputValue
        item.inputVisible = false;
        item.inputValue = '';
      })
      // 获取到的数据不要直接保存到data
      if(this.activeName==='many'){
        this.manyTableData = res.data;
      }else{
        this.onlyTableDate = res.data;
      }
    },

    
    // 级联选择框选中项变化会触发，控制选中范围（只能选三级）
    async handleChange(){
      // 证明选择的不是三级，需要清空
      if(this.selectedCateKeys.length!== 3){
        this.selectedCateKeys = [];
        this.manyTableData = [];
        this.onlyTableDate = [];
        return ;
      }
      this.getParamsList();
      
    },

    // 点击tab页签
    handleTabClick(){
      this.getParamsList();
    },

    // 表单关闭时触发，重置添加对话框
    addDialogClosed(){
      this.$refs.addParamsFormRef.resetFields();
    },

    // 添加参数(预验证)
    addParams(){
      this.$refs.addParamsFormRef.validate(async valid=>{
        if(!valid) return ;
        const {data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
          attr_name:this.addParamsForm.attr_name,
          attr_sel:this.activeName
        });
        
        if(res.meta.status!==201) return this.$message.error('添加参数失败')

        this.$message.success('添加参数成功')
        this.addDialogVisible = false;
        this.getParamsList();
      })
    },

    // 点击修改参数对话框显示
    async showEditDialog(attr_id){
      const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`);

      if(res.meta.status!==200) return this.$message.error('获取参数失败');
      this.editParamsForm = res.data;
      this.editParamsDialogVisible = true;
    },

    // 表单关闭时触发，重置修改对话框
    editDialogClosed(){
      this.$refs.editParamsFormRef.resetFields();
    },

    // 修改参数(预验证)
    editParams(){
      this.$refs.editParamsFormRef.validate(async valid =>{
        if(!valid) return ;
        const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,{
          attr_name:this.editParamsForm.attr_name,
          attr_sel:this.activeName
        });

        if(res.meta.status!==200) return this.$message.error('更新参数失败');
        this.$message.success('更新参数成功');
        this.getParamsList();
        this.editParamsDialogVisible = false;
      })
    },

    // 根据id删除参数
    async removeParams(attr_id){
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err);

      if(confirmResult!=='confirm') return this.$message.info('已取消删除参数');
      const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`);

      if(res.meta.status!==200) return this.$message.error('删除参数失败');

      this.getParamsList();
      return this.$message.success('删除参数成功');

    },

    // 将对attr_vals的操作保存在数据库中
    async saveAttrVals(row){
      const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
      {
        attr_name:row.attr_name,
        attr_sel:row.attr_sel,
        attr_vals:row.attr_vals.join(',')
      });

      if(res.meta.status!==200) return this.$message.error('修改参数失败');
      this.$message.success('修改参数成功');
      row.inputVisible = false;
      row.inputValue = '';
    },

    // 文本框失去焦点或按下enter触发，失去焦点时切换文本框和按钮
    async handleInputConfirm(row){
      // 没有输入内容就在失去焦点时，把文本框清空
      if(row.inputValue.trim().length === 0 ) {
        row.inputValue = '';
        row.inputVisible = false;
        return ;
      }
      // 文本框中有值时，先push进去，再把内容清空，输入框隐藏，此时页面会新增tag，但是数据库没有新增
      row.attr_vals.push(row.inputValue);

      // 发起请求，添加tag
      this.saveAttrVals(row);
      
    },

    // 点击按钮，显示输入框
    showInput(row){
      row.inputVisible=true;

      // 文本框自动获取焦点，页面被重新渲染后，才自动获取焦点
      // eslint-disable-next-line no-unused-vars
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 删除tag
    handleTagClosed(index,row){
      row.attr_vals.splice(index,1);
      this.saveAttrVals(row);
    }

  }
}
</script>

<style lang="less" scoped>
  .cat_opt{
    margin:10px;
    font-size: 14px;
  }

  .attrvals{
    margin-right: 10px;
  }

  .input-new-tag{
    width: 120px;
  }
</style>